<template>

	<view class="content">



		<z-paging ref="paging" bgColor="#1F2630" @query="getList" v-model="list" :hide-empty-view="true">
			<view slot="top">
				<!-- #ifdef APP -->
				<NavBarCommon></NavBarCommon>
				<!-- #endif -->

				<view class="claimBox">
					<image src="@/static/home/right.png" alt="" class="claim1" @click="goBack" />
					<view class="claim2">{{ $t('publiclyraised') }}</view>
				</view>
				<u-gap height="15"></u-gap>
			</view>
			<!-- main -->
			<view>
				<view class="one" style="order: 1">
					<!--  -->
					<view class="recharge-header flex flex-column p-md">
						<view class="flex  items-center justify-between">
							<view class="recharge-header-title">
								<!-- <text>1 NASY ≈ 0.6 USDT</text> -->
							</view>
							<view class="recharge-header-title" @click="golist">
								<text style="font-size: 36rpx;">{{ $t('Exchangerecord') }}</text>
							</view>
						</view>
					</view>
					<u-gap height="15"></u-gap>
					<!--  -->
					<view class="recharge-header flex flex-column p-md" style="background-color: #29313C;">
						<view class="flex  items-center justify-between">
							<view class="recharge-header-title">
								<text>NASY {{ $t('exchange') }}</text>
							</view>
							<view class="recharge-header-title">
								<u-number-box v-model="sol" min="0" :max="Number(1 - total).toFixed(1)" step="0.1"></u-number-box>
							</view>
						</view>
					</view>
					<!--  -->
					<u-gap height="10"></u-gap>
					<!--  -->
					<view class=""
						style="	margin: 0 30rpx;font-size: 28rpx;color: #fff;display: flex;justify-content: space-between;">
						<text>{{ $t('accountbalance') }}: {{ solLimit ? Number(solLimit).toFixed(4) : 0 }} NASY</text>
						<text>{{ $t('consumption') }}: {{ sol || 0 }} SOL</text>
					</view>
					<!-- <view style="	margin: 0 30rpx;font-size: 28rpx;color: #fff;display: flex;justify-content: flex-end;">
						<text>1 NASY ≈ 0.6 USDT</text>
					</view> -->

					<!-- 按钮 -->
	<!-- 				<view class="submitBox" @click="getBtn" :class="sol != '' ? 'active' : ''">
						<view class="submit">{{ $t('exchange') }}</view>
					</view> -->
					<button
					 :disabled="isButtonDisabled" :loading='isButtonDisabled'
					 class="submitBox" @click="getBtn" :class="sol != '' ? 'active' : ''">
						<view class="submit">{{ $t('exchange') }}</view>
					</button>

				</view>
			</view>
			<!--  -->
			<view slot="bottom"></view>
		</z-paging>



	</view>
</template>

<script>
import {
	icoexchange,
	icotransaction,
	icoexchangehistory
} from '@/api/index.js'
import { Connection, Transaction, SystemProgram, LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js'


import env from '@/utils/env.js'
const NETWORK_URL = env.rpcURL
const mintAddress = env.solmintAddress

console.log(mintAddress,'mintAddress sol');
// 创建连接
const connection = new Connection(NETWORK_URL, {
	commitment: 'confirmed',
	confirmTransactionInitialTimeout: 20000  // 5 秒超时
})



export default {
	data() {
		return {
			isButtonDisabled:false,
			solLimit: "",
			sol: '',
			signature: "",
			randomNumber: "",
			form: {},
			list: [],
			total: 0
		}
	},
	computed: {
		maxCount() {
			return (1 - this.total).toFixed()
		}
	},
	methods: {
		// rpc 查询我的资产
		async getSolBalance() {
			let walletAddress = uni.getStorageSync('walletAddress')
			// Main nasy
			try {
				const walletAddress = uni.getStorageSync('walletAddress')
				const publicKey = new PublicKey(walletAddress);
				const balance = await connection.getBalance(publicKey);
				if (balance) {
					this.solLimit = balance / 1e9
				} else {
					console.log('balance not exist');
				}
				console.log(this.solLimit,'Token 余额');
			} catch (err) {
				console.error("查询 SPL Token 余额失败:", err);
				return 0;
			}
		},
		/* 兑换 */
		async icoexchangeApi() {
			let data = {
				"address": uni.getStorageSync('walletAddress'),
				"sol": this.sol,
				"cxc": this.randomNumber,
				"hx": this.signature
			}
			let res = await icoexchange(data)
			if (res.code == 200) {
				this.isButtonDisabled = false
				
				uni.showToast({
					title: "兑换成功",
					icon: "none"
				})
				this.sol = 0
				this.icoexchangehistoryApi()
			}
		},
		/* 获取所有1的数量详情 */
		async icoexchangehistoryApi() {
			let address = uni.getStorageSync('walletAddress')
			let res = await icoexchangehistory(address)
			if (res.code == 200) {
				if (res.data.length != 0) {
					this.total = res.data.reduce((c, r) => {
						return c += r.sol
					}, 0)
					// this.total = this.total.toFixed(1)
					// console.log(this.total,'this.total');
				} else {
					this.total = 0
				}
				this.sol = 0
				console.log(this.total, 'this.total');
			}
		},
		// 构建兑换交易
		async icotransactionApi() {
			this.isButtonDisabled = true
			let data = {
				"address": uni.getStorageSync('walletAddress'),
				"amount": this.sol,
				// "amount": 0.01,
			}
			let res = await icotransaction(data)
			if (res.code == 200) {
				/* 交换nasy金额 */
				this.randomNumber = res.data.tAmount
				uni.hideLoading({})
				let serializedTransaction = res.data.serializedTransaction.data
				if (serializedTransaction) {
					console.log('发送广播');
					const txBuffer = new Uint8Array(serializedTransaction);
					const transaction = Transaction.from(txBuffer);
					// const { signature } = await window.solana.signAndSendTransaction(transaction);
					let signature = ''
					let signAndSendTransaction = {
						signature:''
					}
					try{
						 signAndSendTransaction = await window.solana.signAndSendTransaction(transaction);
					}catch(e){
						console.log('e',e);
						this.isButtonDisabled = false
						uni.showToast({
							title: '拒绝交易',
							icon: "error"
						})
						return;
					}
					signature =  signAndSendTransaction.signature
					console.log("交易签名:", signature);
					// 等待确认
					try {
						const confirmation = await connection.confirmTransaction(signature, 'confirmed')
						if (confirmation.value.err) {
							console.log('交易确认失败');
							this.isButtonDisabled = false
							
							uni.showToast({
								title: '交易不合法',
								icon: "error"
							})
							throw new Error('交易确认失败')
						}
						if (signature) {
							console.log('signature 交易存在', signature);
							this.signature = signature
							/* 保存记录 */
							this.icoexchangeApi()
						}
					} catch (err) {
						this.isButtonDisabled = false
						
						uni.showToast({
							title: '网络错误,请更换节点',
							icon: 'none'
						})
						console.log('err network', err);
					}
				}
			}else{
				this.isButtonDisabled = false
				
			}
		},
		/*  */
		async getBtn() {
			/*  */
			if (this.sol == '' || this.sol == 0) {
				uni.showToast({
					title: "额度不能为空",
					icon: 'none'
				})
				return
			}
			await this.getSolBalance()
			// solLimit 自己的
			// sol 输入的 
			if(this.sol >= this.solLimit ){
				uni.showToast({
					title: "sol不足",
					icon: 'none'
				})
				return
			}
			
			
			// 构建交易
			uni.$u.debounce(this.icotransactionApi, 500)
			
			// this.icotransactionApi()
			console.log('sol', this.sol);
		},
		/*  */
		getList() {
			this.icoexchangehistoryApi()
			// this.getSolBalance()
			this.$refs.paging.complete([]);
		},
		feeCxc() {
			return Number(this.sol) * 0.001
		},
		/*  */
		golist() {
			console.log('golist');
			uni.navigateTo({
				url: '/pages/icuList/icuList'
			})
		},
		goBack() {
			// this.icoexchangeApi()
			// this.icotransactionApi()
			uni.navigateBack()
		},
	},
	onShow() {
		// this.icoratioApi()
	}
}
</script>




<style scoped lang="scss">
.recharge-tag {
	display: flex;
	justify-content: space-between;
	margin: 0 30rpx;

	.recharge-tag-left {
		text {
			font-family: Source Han Sans CN;
			font-weight: 300;
			font-size: 24rpx;
			color: #FFFFFF;
			line-height: 64rpx;
		}
	}

	.recharge-tag-right {
		text {
			font-family: Source Han Sans CN;
			font-weight: 300;
			font-size: 24rpx;
			color: #FFFFFF;
			line-height: 64rpx;
		}
	}
}

.mev-follow-robot-search-wrap {
	margin: 0 30rpx;

	height: 108rpx;
	background: #29313C;
	border-radius: 30rpx;
	border: 2rpx solid #6C7680;
	display: flex;
	align-items: center;
	justify-content: 0;

	.mev-follow-robot-search-wrap-icon {
		margin: 30rpx 20rpx 30rpx 30rpx;
		width: 48rpx;
		height: 48rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.mev-follow-robot-search-wrap-input {
		display: flex;
		align-items: center;

		input {
			color: white;
		}
	}

	.mev-follow-robot-search-wrap-select {
		display: flex;
		align-items: center;

		.mev-follow-robot-search-wrap-select-label {
			font-family: Source Han Sans CN;
			font-weight: bold;
			font-size: 24rpx;
			color: #45E5AF;
			line-height: 64rpx;
		}

		.mev-follow-robot-search-wrap-select-icon {
			width: 20rpx;
			height: 12rpx;
			margin-left: 16rpx;
			margin-right: 36rpx;
		}
	}
}

.recharge-header {
	display: flex;
	// align-items: center;
	// justify-content: space-between;
	// margin: 0 30rpx;
	justify-content: space-between;



	.recharge-header-back-icon {
		margin-right: 26rpx;

		image {
			width: 22rpx;
			height: 38rpx;
		}
	}

	.recharge-header-title {
		text {
			font-family: Source Han Sans CN;
			font-weight: bold;
			font-size: 36rpx;
			color: #FFFFFF;
			// line-height: 64rpx;
			line-height: 36rpx;
		}
	}

	.recharge-header-subtitle {
		// vertical-align: bottom;
		display: flex;
		align-items: end;

		/* 使元素垂直居中 */
		text {
			font-family: Source Han Sans CN;
			font-weight: 300;
			font-size: 24rpx;
			color: #45E5AF;
			// line-height: 64rpx;
		}
	}

}




/*  */
.wallet-avatar-gap {
	border-radius: 40rpx;
	background-color: #4a90e2;
	width: 80rpx;
	height: 80rpx;
	margin-right: 31rpx;
}

.content {
	width: 100%;
	min-height: 100vh;
	background-color: #1f2630;
}

.claimBox {
	display: flex;
	justify-content: center;

	align-items: center;
	padding-top: 50rpx;
	position: relative;

	.claim1 {
		position: absolute;
		left: 2%;
		width: 22rpx;
		height: 38rpx;
	}

	.claim2 {
		font-weight: 500;
		font-size: 36rpx;
		color: #ffffff;
		// margin-left: 275rpx;
	}
}

.addressOne {
	display: flex;
	align-items: center;
	margin-top: 59rpx;
	margin-left: 30rpx;

	.tp {
		width: 100rpx;
		height: 100rpx;
	}

	.address {
		font-weight: 300;
		font-size: 36rpx;
		color: #ffffff;
		margin-left: 21rpx;
	}

	.down {
		width: 25rpx;
		height: 14rpx;
		margin-left: 20rpx;
	}
}

.picBox {
	width: 690rpx;
	height: 420rpx;

	// background-image: url("/static/home/nine.png");
	background: url('/static/home/nine.png') no-repeat;

	background-size: 100%;

	margin-left: 30rpx;
	margin-right: 30rpx;
	margin-top: 30rpx;

	.picOne {
		display: flex;
		align-items: center;
		padding-top: 30rpx;

		.pic1 {
			width: 44rpx;
			height: 48rpx;
			margin-left: 22rpx;
		}

		.num1 {
			font-size: 30rpx;
			color: #ffffff;
			margin-left: 11rpx;
		}

		.num2 {
			font-size: 48rpx;
			color: #ffffff;
			margin-left: 45rpx;
		}

		.pic2 {
			width: 35rpx;
			height: 23rpx;
			margin-left: 20rpx;
		}
	}

	.drawDownBox {
		display: flex;
		align-items: center;
		justify-content: space-around;
		margin-top: 63rpx;

		.drawOne {
			// margin-left: 46rpx;
			text-align: center;

			.one {
				font-size: 36rpx;
				color: #ffffff;
			}

			.one1 {
				font-size: 24rpx;
				color: #8e8e8f;
			}
		}

		.drawTwo {
			// margin-left: 125rpx;
			text-align: center;

			.two {
				font-size: 36rpx;
				color: #ffffff;
			}

			.two2 {
				font-size: 24rpx;
				color: #8e8e8f;
			}
		}

		.drawThree {
			// margin-left: 134rpx;
			text-align: center;

			.three {
				font-size: 36rpx;
				color: #ffffff;
			}

			.three3 {
				font-size: 24rpx;
				color: #8e8e8f;
			}
		}
	}
}

.progress-container {
	width: 600rpx;
	display: flex;
	margin: 0 auto;
	align-items: center;
	// background-color: #333;
	border-radius: 10px;
	// overflow: hidden;
	// margin-left: 45rpx;
	// margin-top: 60rpx;
	position: relative;
	flex-direction: column;
}

.progress-bar {
	width: 600rpx;
	height: 20rpx;
	// background-color: #ffcc00;
	border-radius: 12px;

	background: linear-gradient(to right, #ffcc00 var(--difference-percentage), #1F2631 0%);
	/* 黄色 */
	transition: width 0.5s ease-in-out;
}

.percentage {
	// position: absolute;
	// top: 41%;


	// left: 40%;
	// right: 10px;

	font-size: 72rpx;
	color: #fcd434;
}

.submitBox {
	width: 690rpx;
	height: 88rpx;
	background: #29313C;
	border-radius: 44rpx;
	margin-top: 60rpx;
	margin-left: 30rpx;


	.submit {
		font-weight: bold;
		font-size: 36rpx;
		color: #0d081a;
		line-height: 80rpx;
		text-align: center;
	}
}

.active {
	background: #fcd434 !important;
}
</style>